package com.qire.manhua.dal.service;

import android.app.Activity;

import com.qire.antsbinder.dal.DataService;
import com.qire.antsbinder.dal.annotation.StrategyAnnotation;
import com.qire.antsrouter.lifecycleHandler.ActivityManageHandler;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.basic.StringUtil;
import com.qire.common.constant.Url;
import com.qire.common.dal.WarehouseFactory;
import com.qire.common.utils.Logger;
import com.qire.common.utils.ToastHelper;
import com.qire.manhua.dal.ITradingDataDAL;
import com.qire.manhua.dal.IUserDataDAL;
import com.qire.manhua.model.entity.OrderEntity;
import com.qire.manhua.model.enumeration.PaymentMethod;
import com.qire.manhua.model.viewModel.impl.BuyCoinsMarketDialogViewModel;
import com.qire.manhua.model.vo.MarketInfoVO;
import com.qire.manhua.model.vo.TradingOrderVO;
import com.qire.manhua.model.vo.TradingVerifyResponseVO;
import com.qire.manhua.model.vo.UserDetailVO;
import com.qire.other.thirdPlatform.AliPayPlatform;
import com.qire.other.thirdPlatform.WeChatPlatform;

public class BuyCoinsMarketDialogService extends DataService {

    private final ITradingDataDAL tradingDataDAL = WarehouseFactory.create(this, ITradingDataDAL.class);
    private final IUserDataDAL userDataDAL = WarehouseFactory.create(this, IUserDataDAL.class);

    private final BuyCoinsMarketDialogViewModel viewModel;

    public BuyCoinsMarketDialogService(BuyCoinsMarketDialogViewModel viewModel) {
        this.viewModel = viewModel;
    }

    /** 加载金币金豆市场信息 */
    public void loadMarketInfo() {
        tradingDataDAL.fetchMarketWelfareInfo();
    }
    @StrategyAnnotation(event = Url.MarketWelfareInfo)
    public void fetchMarketWelfareInfoCallback(MarketInfoVO marketInfoVO, boolean isCache) {
        viewModel.loadMarketInfo(marketInfoVO.toMarketInfo());
    }

    /**
     * 创建金币充值订单
     * @param orderEntity
     * @param paymentMethod
     * @param fromPayActivity
     */
    public void createOrder(OrderEntity orderEntity, PaymentMethod paymentMethod, String fromPayActivity) {
        switch (paymentMethod) {
            case WeChatPay:
                tradingDataDAL.createWeChatOrder(orderEntity.fee,  orderEntity.productId, 1, orderEntity.bookId, fromPayActivity);
                return;
            case AliPay:
                tradingDataDAL.createAliPayOrder(orderEntity.fee,  orderEntity.productId, 1, orderEntity.bookId, fromPayActivity);
                return;
        }
    }
    @StrategyAnnotation(event = Url.WeChatPlaceOrder)
    public void createWeChatOrderCallback(TradingOrderVO orderVO, boolean isCache) {
        // 微信支付
        if(ObjectUtil.isNull(orderVO) || StringUtil.isEmpty(orderVO.ok)) {
            ToastHelper.showToast("创建订单失败");
            return;
        }

        TradingOrderVO.PayParamVO payParamVO = orderVO.payParam;
        if(ObjectUtil.isNull(payParamVO)) {
            ToastHelper.showToast("创建订单失败 payParam 为空");
            return;
        }
        Logger.d(payParamVO.toString());

        WeChatPlatform.PayParam payParam = new WeChatPlatform.PayParam(payParamVO.appId, payParamVO.partnerId, payParamVO.prepayId,
                payParamVO.nonceStr, payParamVO.timeStamp, payParamVO.sign, orderVO.outTradeNo);

        WeChatPlatform.WeChat.goPay(payParam, null,(msg, payCode, resultInfo) -> {
            String outTradeNo = (String) resultInfo;
            switch (payCode) {
                case WeChatPlatform.PAY_SUCCESS : {
                    tradingSyncVerify(PaymentMethod.WeChatPay, outTradeNo, "");
                    break;
                }
//                case WeChatPlatform.PAY_ERROR : {
//                    break;
//                }
//                case WeChatPlatform.PAY_CANCEL : {
//                    break;
//                }
            }
        });
    }
    @StrategyAnnotation(event = Url.AliPayPlaceOrder)
    public void createAliPayOrderCallback(TradingOrderVO orderVO, boolean isCache) {
        // 支付宝支付
        if(ObjectUtil.isNull(orderVO) || StringUtil.isEmpty(orderVO.ok)) {
            ToastHelper.showToast("创建订单失败");
            return;
        }


        if(StringUtil.isEmpty(orderVO.strJson)) {
            ToastHelper.showToast("创建订单失败 strJson");
            return;
        }

        Logger.d(orderVO.strJson);

        String outTradeNo = orderVO.outTradeNo;
        Activity activity = ActivityManageHandler.HANDLER.currentActivity();
        AliPayPlatform.AliPay.goPay(orderVO.strJson, activity, (msg, payCode, resultInfo) -> {
            switch (payCode) {
                case AliPayPlatform.PAY_SUCCESS : {
                    ToastHelper.showToast("支付成功");
                    tradingSyncVerify(PaymentMethod.AliPay, outTradeNo, (String) resultInfo);
                    break;
                }
                case AliPayPlatform.PAY_ERROR : {
                    ToastHelper.showToast("支付失败");
                    break;
                }
                case AliPayPlatform.PAY_CANCEL : {
                    ToastHelper.showToast("支付取消");
                    break;
                }
            }
        });
    }

    /**
     * 支付结束后同步交易结果校验
     * @param paymentMethod 交易类型
     */
    private void tradingSyncVerify(PaymentMethod paymentMethod, String outTradeNo, String aliPayResult) {
        viewModel.noticeNewcomerRewardIfNeed();
        switch (paymentMethod) {
            case WeChatPay:
                tradingDataDAL.tradingWeChatVerify(outTradeNo);
                return;
            case AliPay:
                tradingDataDAL.tradingAliPayVerify(outTradeNo, aliPayResult);
                return;
        }
    }
    @StrategyAnnotation(event = {Url.WeChatTradeVerify, Url.AliPayTradeVerify})
    public void tradeVerifyResponse(TradingVerifyResponseVO responseVO, boolean isCache) {
        refreshUserDetailData();

        //因为后台不一定及时收到第三方支付的回调，所以这个提示不一定准确
//        if(responseVO.payState == 0){
//            ToastHelper.showToast("订单未支付");
//            return;
//        }

        if(responseVO.activityState == 0) {
            // 没给活动地址
            viewModel.showBuyResult(responseVO.ware.orderCoin, responseVO.ware.awardBean);
        } else {
            // 给了活动地址
            viewModel.showSpecialEvent(responseVO.webImgUrl, responseVO.webPageUrl);
        }
    }

    /**
     * 同步刷新用户资料，更新余额
     */
    private void refreshUserDetailData() {
        userDataDAL.refreshUserDetailData();
    }
    @StrategyAnnotation(event = Url.myIndex)
    public void requestMyIndexDataCallback(UserDetailVO dataVO, boolean isCache) {
        if(isCache || dataVO == null) return;
        dataVO.updateUserEntity();
    }
}
